package net.huashitong.common.util;

import com.sirdc.modules.core.exceptions.ServiceException;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.date.DateUtils;
import net.huashitong.common.entity.SysMessage;
import net.huashitong.common.enums.MsgStatusEnum;
import net.huashitong.common.service.SysMessageService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 短信发送定时任务
 */
public class SendMsgJob implements Job {

    private static final Logger LOGGER = LoggerFactory.getLogger(SendMsgJob.class);
    @Autowired
    private SysMessageService sysMessageService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        LOGGER.info(String.format("系统发送消息任务 SendMsgJob !  时间:" + DateUtils.getDateTime()));
        List<SysMessage> sysMessages = sysMessageService.querySendList();
        if (ObjectUtils.isBlank(sysMessages) || sysMessages.size() == 0) {
            return;
        }
        for (SysMessage sysMessage : sysMessages) {
            boolean isSuccess = false;
            try {
                if (sysMessage.getEsType().equals(MsgStatusEnum.EMAIL.getCode())) {
                } else if (sysMessage.getEsType().equals(MsgStatusEnum.SMS.getCode())) {
                    //YunpianSmsHelper.sendSms(sysMessage);
                } else if (sysMessage.getEsType().equals(MsgStatusEnum.WX.getCode())) {
                    //PushApiUtils.publishMessage();
                }
            } catch (Exception e) {
                LOGGER.error(e.getMessage(),e);
            }
            Integer sendNum = Integer.valueOf(sysMessage.getEsSendNum());
            try {
                // 发送消息成功
                if (isSuccess){
                    sysMessage.setEsSendStatus(MsgStatusEnum.SUCCESS.getCode());
                } else {
                    throw new ServiceException("发送消息出现异常");
                }
            } catch (Exception e) {
                // 发送消息出现异常
                sysMessage.setEsSendStatus(MsgStatusEnum.FAIL.getCode());
            }
            sysMessage.setEsSendNum(++sendNum+"");
            // 发送结果回写到数据库
            sysMessageService.update(sysMessage);
        }
    }

}
